//
//  ViewController.m
//  runteraters
//
//  Created by Sebastian Borggrewe on 16/11/2011.
//  Copyright (c) 2011 Robolo. All rights reserved.
//

#import "HunterController.h"
#import "NetworkingCenter.h"
#import "LocationMessage.h"

@implementation HunterController

@synthesize txtDistance, txtDirection, txtUpdateInterval;
@synthesize imgCompass;

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - Location Delegate
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    
    // Update Frequency
    numberOfUpdates++;
    NSTimeInterval timeSinceLastUpdate = ([[NSDate date] timeIntervalSince1970] - lastUpdate);
    updateFrequency = (updateFrequency*((numberOfUpdates-1)/numberOfUpdates)) + (timeSinceLastUpdate*(1/numberOfUpdates));
    lastUpdate = [[NSDate date] timeIntervalSince1970];
    
    //NSLog(@"Update frequency: %f, time since last update: %f",updateFrequency,timeSinceLastUpdate);
    
    
    [txtUpdateInterval setText:[NSString stringWithFormat:@"%f sec",updateFrequency]];
    
    double lat1 = [self toRadian:newLocation.coordinate.latitude];
    double lat2 = [self toRadian:goTo.coordinate.latitude];
    double dLon = [self toRadian:(goTo.coordinate.longitude - newLocation.coordinate.longitude)];
    
    double y = sin(dLon) * cos(lat2);
    double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
    
    currentDirection = atan2(y, x);
    
    //NSLog(@"currentDirection: %f",currentDirection);
    
    [txtDistance setText:[NSString stringWithFormat:@"%f", [newLocation distanceFromLocation:goTo]]];
    
    // Update server
    LocationMessage *locationMessage = [[LocationMessage alloc] initWithPlayer:@"sebs" latitude:newLocation.coordinate.latitude longitude:newLocation.coordinate.latitude];
    
    [[NetworkingCenter defaultServer] sendMessage:locationMessage];
    
    [locationMessage release];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
    currentHeading = [self toRadian:newHeading.trueHeading];
    
    if(currentHeading != -1 && currentDirection != -1)
        [self updateArrowView];
}

/*
 * Show compass calibration
 */
- (BOOL)locationManagerShouldDisplayHeadingCalibration:(CLLocationManager *)manager {
    return YES;
    //return NO;
}

- (void) updateArrowView {
    //NSLog(@"Update Arrow: %f", currentRotation);
    
    double currentArrowDirection = currentDirection - currentHeading;
    
    double currentArrowDirectionInDegrees = [self toBearing:currentArrowDirection];
    
    [txtDirection setText:[NSString stringWithFormat:@"Degrees:%f",currentArrowDirectionInDegrees]];
    
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    
    [UIView animateWithDuration:0.1f animations:^(void) {
        imgCompass.transform = CGAffineTransformMakeRotation(currentArrowDirection);
    }];
    
    currentRotation = currentArrowDirection;
}

#pragma mark - Heading
- (double) toRadian: (double) val
{
    return val * (M_PI / 180);
}

// Convert to degrees from radians
- (double) toDegrees: (double) val
{
    return val * 180 / M_PI;
}

// convert from a radian to a 360 degree format.
- (double) toBearing: (double) val
{
    return ( (int)([self toDegrees: val]) + 360 ) % 360;        // use mod to get the degrees
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSLog(@"launched view");
    [[NetworkingCenter defaultServer] openConnectionToServer];
    
	// Do any additional setup after loading the view, typically from a nib.
    
    goTo = [[CLLocation alloc] initWithLatitude:50.77890 longitude:6.05907];
    
    // Init direction and heading variable
    currentHeading = -1;
    currentDirection = -1;
    
    // Init Location Manager
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self;
    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [locationManager startUpdatingLocation];
    [locationManager startUpdatingHeading];
    
    currentRotation = 0;
    numberOfUpdates = 1;
    
    lastUpdate = [[NSDate date] timeIntervalSince1970];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveNetworkingNotification:) 
                                                 name:NETWORKING_NOTIFICATION
                                               object:nil];
    
}

- (void) receiveNetworkingNotification:(NSNotification *) notification
{
    if (![[notification name] isEqualToString:NETWORKING_NOTIFICATION]) return;
    
    // Only if it is a Networking Nofitication
    NSLog(@"Received Notification: %@",[((NetworkMessage*)[notification object]) stringMessage]);
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
	[super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];
}

@end
